package commonFunction;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.Reporter;

public class ScreenShotOnFailure {

	WebDriver driver;
	private final static String SCREEN_SHOT_PATH = "test-output/screen-shot";
	private static String SCREEN_SHOT_NAME = null;
	
	SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
	Calendar cal = Calendar.getInstance();
	Date date = cal.getTime();
	String dateStr = sf.format(date);

	public void takeScreentShot() throws IOException {
		File screenShotDir = new File(SCREEN_SHOT_PATH);
		if (!screenShotDir.exists()) {
			screenShotDir.mkdirs();
		}

		// SCREEN_SHOT_NAME = String.valueOf(new Date().getTime()) + ".jpg";
		SCREEN_SHOT_NAME = this.getClass().getSimpleName() + "_" + dateStr + ".jpg";
		FileUtils.copyFile(((TakesScreenshot) this.getDriver()).getScreenshotAs(OutputType.FILE),
				new File(SCREEN_SHOT_PATH + "/" + SCREEN_SHOT_NAME));

		//Image
//		Reporter.log("<img src= \"../screen-shot/" + SCREEN_SHOT_NAME + "\">");
		
		//Link  
		Reporter.log("<a href=../screen-shot/" + SCREEN_SHOT_NAME + " target=_blank>Failed Screen Image："+SCREEN_SHOT_NAME+"</a>", true); 
	}

	public static String getScreenShotPath() {
		return SCREEN_SHOT_PATH;
	}

	public static String getScreenShotName() {
		return SCREEN_SHOT_NAME;
	}

	public WebDriver getDriver() {
		return driver;
	}

	public void setDriver(WebDriver driver) {
		this.driver = driver;
	}

}
